<?php

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

class RolesController extends Controller
{
    private $role;

    public function __construct()
    {
        $this->role = new Context(new Role());
    }
    public function index()
    {
        $roles = $this->role->display(10,function($query){
            if(request('name'))
            {
                $query->where('name',request()->input('name'))->orWhere('desc','like','%'.request()->input('name').'%');
            }
        });
         return $this->success(['roles'=>$roles]);
    }

    public function show($id)
    {
        //展示全部角色
        if($id == 0)
        {
            return $this->success($this->role->display(0,function($query){
                if(request()->input('keyword'))
                {
                    $query->where('desc','like','%'.request()->input('keyword').'%');
                }
            }));
        }else{
            $roles = $this->role->find($id);
            $perms = $roles->permissions()->get(['id','desc','name']);
            return $this->success(['roles' => $roles , 'perms' => $perms]);
        }
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|alpha_dash|unique:roles,name',
        ]);
        if($role = $this->role->create($request->only('name','desc'))){
            // //添加权限
            // $role->givePermissionTo(explode(',', $request->perms));
             return $this->success(['message'=>'添加成功']);
        };
        return $this->error('添加失败');
    }

    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'name' => 'required|alpha_dash|unique:roles,name,'.request()->route('role'),
        ]);
        if($this->role->update($id,$request->only('name','desc'))){
            //$role->syncPermissions(explode(',', $request->perms));
        };
        return $this->success(['message'=>'更新成功']);
    }

    public function destroy(Role $role)
    {
        if($role->name == 'super_admin')
        {
             return $this->error('超级管理员角色不能删除');
        }
        if($role->delete())
        {
            return $this->success(['message'=>'删除成功']);
        }else{
              return $this->error('删除失败');
        }
    }
}
